package com.qingmu.club.minaapi.controller.club;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingmu.club.minaapi.custom.logic.ClubStaffShopLogic;
import com.qingmu.club.minaapi.custom.logic.EvaluationLogic;
import com.qingmu.club.minaapi.custom.logic.UsersWxLogic;
import com.qingmu.club.minaapi.enums.UserClassHoursStatusEnum;
import com.qingmu.club.minaapi.model.MiniLoginModel;
import com.qingmu.club.minaapi.plus.entity.*;
import com.qingmu.club.minaapi.plus.service.*;
import com.qingmu.club.minaapi.utils.*;
import com.qingmu.club.minaapi.wechat.WechatUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 会员微信资料 前端控制器
 * </p>
 *
 * @author duke
 * @since 2019-08-20
 */
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@Api(value = "用户登录(俱乐部端小程序)", description = "用户登录(俱乐部端小程序)")
@RequestMapping("/club/users")
public class ClubUserController {

    @Autowired
    EvaluationService evaluationService;

    @Autowired
    ClubStaffService clubStaffService;

    @Autowired
    EvaluationLogic evaluationLogic;

    @Autowired
    ClubStaffShopLogic clubStaffShopLogic;

    @Autowired
    UsersWxService usersWxService;

    @Autowired
    ClubUsersService clubUsersService;

    @Autowired
    UsersWxLogic usersWxLogic;

    @Autowired
    ClubShopService clubShopService;

    @Autowired
    ClubStaffShopService clubStaffShopService;

    @Value("${web.upload-path}")
    private String uploadPath;
    @Value("${web.imageService}")
    private String wanPath;


    private final static Logger logger = LoggerFactory.getLogger(ClubUserController.class);


    @RequestMapping(value = "/createQrCode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "生成人员二维码")
    public ResponseEntity createQrCode(
            @ApiParam(required = true, value = "俱乐部人员ID") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "俱乐部门店ID") @RequestParam(required = true) String shopId,
            @ApiParam(required = true, value = "人员身份") @RequestParam(required = true) String staffTag
    ) {
        Integer Tag = 0 ;//  * 人员角色0-教练1-课程顾问2-店主3-管理员
        if(staffTag.equals(KeyValueDefine.COACH)){
            Tag = 0 ;
        }else if(staffTag.equals(KeyValueDefine.COUNSELOR)){
            Tag = 1 ;
        }else if(staffTag.equals(KeyValueDefine.SHOPOWNER)){
            Tag = 2 ;
        }else {
            Tag = 3 ;
        }

        QueryWrapper<ClubStaffShop> qw = new QueryWrapper<>();
        qw.eq(ClubStaffShop.STAFF_ID,staffId).eq(ClubStaffShop.SHOP_ID,shopId).eq(ClubStaffShop.STAFF_TAG,Tag);
        ClubStaffShop clubStaffShop = this.clubStaffShopService.getOne(qw);
        if(clubStaffShop==null){
            return ResponseObject.error(553, "人员信息出错 请联系管理员");
        }
        String qrCode = WechatUtil.createMiniQrcode(uploadPath, clubStaffShop.getId());
        if (StringUtils.isEmpty(qrCode)) {
            return ResponseObject.error(556, "二维码生成失败");
        }
        HashMap<String,Object> map = new HashMap<>();
        map.put("qrCodeUrl",wanPath+qrCode);
        return ResponseObject.success(map);
    }

    @RequestMapping(value = "/updateStaffShop", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "修改人员门店")
    public ResponseEntity updateStaffShop(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId
    ) {
        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"教练信息找不到");
        }
        ClubShop clubShop = this.clubShopService.getById(shopId);
        if(clubShop==null){
            return ResponseObject.error(601,"门店信息找不到");
        }
        clubStaff.setDefaultShopId(clubShop.getId());
        clubStaff.setDefaultShopName(clubShop.getShopName());
        boolean state = this.clubStaffService.updateById(clubStaff);
        if(!state){
            return ResponseObject.error();
        }
        return ResponseObject.success();
    }

    @RequestMapping(value = "/queryStaff", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询人员信息")
    public ResponseEntity queryStaff(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "人员身份") @RequestParam(required = true) String staffTag
    ) {
        ClubStaff clubStaff = this.usersWxLogic.getClubStaff(staffId);
        if (clubStaff == null) {
            return ResponseObject.error(401, "教练信息找不到");
        }
        List<HashMap<String, Object>> shopList = this.clubStaffShopLogic.queryShopList(staffId, staffTag,clubStaff);
        if (CollectionUtils.isEmpty(shopList)) {
            return ResponseObject.error(601, "教练未绑定门店");
        }

        HashMap<String, Object> map = ConvertUtil.objectToMap(clubStaff);
        String evaluationStar = this.evaluationLogic.coachEvaluationStar(staffId);
        map.put("evaluationStar", evaluationStar);
        map.put("shopList", shopList);

        return ResponseObject.success(map);
    }

    @RequestMapping(value = "/getEvaluation", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询会员对教练的评价")
    public ResponseEntity getEvaluation(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId
    ) {
        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"教练信息找不到");
        }
        QueryWrapper<Evaluation> qw = new QueryWrapper<>();
        qw.eq(Evaluation.COACH_ID,staffId).orderByDesc(Evaluation.CREATE_TIME);
        List<Evaluation> evaluationList = this.evaluationService.list(qw);

        return ResponseObject.success(evaluationList);
    }

    @RequestMapping(value = "/verify", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "人员身份确认")
    public ResponseEntity verify(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = false, value = "是否教练") @RequestParam(required = false) String isCoach,
            @ApiParam(required = false, value = "是否课程顾问") @RequestParam(required = false) String isCounselor,
            @ApiParam(required = false, value = "是否管理层") @RequestParam(required = false) String isManager,
            @ApiParam(required = false, value = "是否店主") @RequestParam(required = false) String isShopowner,
            HttpServletRequest request
    ) {
        logger.info(Utils.getRequstUrl(request));

        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"教练信息找不到");
        }

        QueryWrapper qw = new QueryWrapper();
        qw.eq(ClubStaff.ID,staffId);
        qw.eq(!StringUtils.isEmpty(isCoach),ClubStaff.IS_COACH,isCoach);
        qw.eq(!StringUtils.isEmpty(isCounselor),ClubStaff.IS_COUNSELOR,isCounselor);
        qw.eq(!StringUtils.isEmpty(isManager),ClubStaff.IS_MANAGER,isManager);
        qw.eq(!StringUtils.isEmpty(isShopowner),ClubStaff.IS_SHOPOWNER,isShopowner);

        ClubStaff clubStaff2 = this.clubStaffService.getOne(qw);
        if(clubStaff2==null){
            return ResponseObject.error(556,"暂无权限");
        }
        clubStaff2.setSysPassword(null);//不返回密码
        return ResponseObject.success(clubStaff2);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "小程序授权获取手机号")
    public ResponseEntity login(
            @RequestBody(required = true) MiniLoginModel miniLoginModel,
            HttpServletRequest request
    ) {
        try {
            logger.info(Utils.getRequstUrl(request));
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

            url = String.format(url, WechatUtil.clubAppId, WechatUtil.clubAppSecret, miniLoginModel.getCode());
            String content = HttpUtils.requestGet(url, null, null);

            if (content == null) {
                return ResponseObject.error(ResponseObject.ResponseCode_NOT_FOUNDED,"解密失败");
            }

            HashMap<String, Object> returnMap = Utils.stringToMap(content);
            String openid = (String) returnMap.get("openid");
            String session_key = (String) returnMap.get("session_key");
            if (StringUtils.isEmpty(openid)) {
              return ResponseObject.error(ResponseObject.ResponseCode_NOT_FOUNDED,"openid获取失败");
            }

            String result = Utils.decrypt(miniLoginModel.getEncryptedData(), session_key, miniLoginModel.getIv(), "UTF-8");
            if (StringUtils.isEmpty(result)) {
                return ResponseObject.error(ResponseObject.ResponseCode_NOT_FOUNDED,"解密失败");
            }

            HashMap<String, Object> hashMap = ConvertUtil.stringToMap(result);
            String staffMobile = (String) hashMap.get("phoneNumber");

            QueryWrapper<ClubStaff> qw = new QueryWrapper<>();
            qw.eq(ClubStaff.STAFF_MOBILE,staffMobile).eq(ClubStaff.STATUS, KeyValueDefine.ONLINE_STATUS);
            ClubStaff clubStaff = this.clubStaffService.getOne(qw);
            if(clubStaff==null){
                return ResponseObject.error(603,"该手机号暂无权限");
            }
            clubStaff.setSysPassword(null);//不返回密码

            QueryWrapper<UsersWx> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(UsersWx.USER_ID,clubStaff.getId());
            UsersWx usersWx = this.usersWxService.getOne(queryWrapper);
            if(usersWx==null){
                UsersWx user = new UsersWx();
                user.setOpenId(openid);
                user.setUserId(clubStaff.getId());
                user.setType(1);//俱乐部端
                boolean falg = this.usersWxService.save(user);
                if(!falg){
                    return ResponseObject.error(556,"添加openid失败!");
                }
            }

            return ResponseObject.success(clubStaff);

        } catch (Exception e) {
            e.printStackTrace();
            LoggerFactory.getLogger(this.getClass()).error(e.getMessage());
            return ResponseObject.error(ResponseObject.ResponseCode_SYS_ERROR,"系统繁忙");
        }
    }


}

